<template>
  <div class="markDialogContainer" v-drag>
    <div class="markDialogTitle drag-handle">
      <div class="title-left">
        <div class="bar"></div>
        <div class="title-text">地图书签</div>
      </div>
      <div class="title-right">
        <div tabindex="0" class="icon" @click="closeDialog">×</div>
      </div>
    </div>
    <div class="markDialogContent">
      <div class="contentBox">
        <div class="formRow">
          <div class="search_label">快速检索</div>
        </div>
        <div class="formRow">
          <div class="search_input">
            <input
              type="text"
              class="searchContent"
              placeholder="请输入需要检索的关键字"
              v-model="searchValue"
            />
          </div>
          <el-button type="primary" icon="el-icon-search" @click="searchMark">
            查询
          </el-button>
        </div>
        <div class="formRow formRow1">
          <div class="search_label">已有书签列表</div>
        </div>
        <div class="formRow formTable">
          <div class="control">
            <div
              class="data-container"
              v-for="(item, index) in markTableData"
              :key="index"
              @click="panToMark(item, index)"
            >
              <div class="data-item">
                {{ item.mapBookmarkName }}
              </div>
              <div class="data-item" style="display: flex; margin: 0">
                <el-button
                  type="text"
                  icon="el-icon-tickets"
                  @click.stop="markItemDetail(item, index)"
                >
                  详情
                </el-button>
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  @click.stop="removeMarkItem(item.mapBookmarkId)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="formRow">
          <div class="control controlBtn">
            <button class="smallBtn" type="button" @click="enableMapClick">
              新增
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- 新增书签对话框 -->
    <div
      v-show="isAddDialogVisible"
      class="add-bookmark-dialog"
      ref="AddDialogVisible"
    >
      <div class="dialog-content">
        <h2>新增书签</h2>
        <el-row>
          <el-col :span="12">
            <div class="form-item">
              名称：
              <el-input
                v-model="newBookmarkName"
                placeholder="输入书签名称"
              ></el-input>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="form-item">
              备注：
              <el-input
                type="textarea"
                v-model="bookmarkNote"
                placeholder="输入备注"
              ></el-input>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="form-item">
              附件：
              <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :limit="1"
                :file-list="fileList"
                :on-success="handleSuccess"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="form-buttons">
              <el-button type="primary" @click="closeAddDialog">取消</el-button>
              <el-button type="primary" @click="addBookmark">添加</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- 书签详情框 -->
    <div
      v-show="isDetailDialogVisible"
      class="add-bookmark-dialog"
      ref="DetailDialogVisible"
    >
      <div class="dialog-content">
        <h2>书签</h2>
        <el-row>
          <el-col :span="12">
            <div class="form-item">
              名称：
              <el-input
                v-model="bookPanel.bookmarkName"
                placeholder="输入书签名称"
              ></el-input>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="form-item">
              备注：
              <el-input
                type="textarea"
                v-model="bookPanel.bookmarkNote"
                placeholder="输入备注"
              ></el-input>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="form-item">
              附件：
              <img style="" :src="'http://' + bookPanel.imageData" alt="" />
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="form-buttons">
              <el-button type="primary" @click="closeDetailDialog"
                >取消</el-button
              >
              <el-button type="primary" @click="addBookmark">添加</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- <addNewBookMark
       :dialogVisible="isAddDialogVisible"
        @update:dialogVisible="isAddDialogVisible = $event">

        </addNewBookMark> -->
  </div>
</template>

<script>
import {
  addBookMark,
  getBookMarkList,
  deleteBookMark,
  searchBookMark,
} from "@/api/quickPosition";
import Overlay from "ol/Overlay";
// import addNewBookMark from './addNewBookMark.vue';
export default {
  components: {},
  props: {
   
  },
  data() {
    return {
      bookPanel: {
        bookmarkName: "",
        bookmarkNote: "",
        imageData: "",
      },
      popup: null,
      popup2: null,
      geomData: null,
      markTableData: [
        { item: "列1的内容1" },
        { item: "列1的内容2" },
        { item: "列1的内容3" },
      ],
      isAddDialogVisible: false,
      isDetailDialogVisible: false,
      newBookmarkName: "",
      bookmarkNote: "",
      fileList: [],
      selectedCoordinates: null, // 存储点击位置的经纬度
      map: null,
      addBookmarkListener: null, // 存储地图点击事件监听器
      markerLayer: null,
      markerNameLayer: null,
      searchValue: "",
    };
  },
  computed: {
   
  },
  watch: {
    dialogVisible(newVal) {},
  },
  methods: {
    handleSuccess(response, file, fileList) {
      // 假设上传成功后服务器会返回文件信息
      this.fileList.push(file); // 将上传成功的文件添加到 fileList 中
    },
    initMap() {
      setTimeout(() => {
        this.map = this.$store.getters.Map;
        if (this.map) {
        } else {
          console.error("地图实例未找到");
        }
      }, 1000); // 延迟 1000 毫秒（1秒）后执行
    },
    handleRemove(file, fileList) {},
    closeDialog() {
      // 通过修改 prop 来关闭弹窗
      this.$emit("update:dialogVisible", false);
    },
    createLayer() {
      setTimeout(() => {
        this.markerLayer = this.map.layer.createVectorLayer("BookMarkerLayer");
        this.markerNameLayer = this.map.layer.createVectorLayer(
          "BookMarkerNameLayer"
        );
        this.map.map.on("click", (e) => {
          const feature = this.map.map.forEachFeatureAtPixel(e.pixel, (f) => {
            return f;
          });
          if (feature && feature.values_.markerInfo != undefined) {
            let elPopup = this.$refs.DetailDialogVisible;
            this.popup2 = new Overlay({
              element: elPopup,
              position: null,
              offset: [0, -8],
              positioning: "bottom-center",
            });
            this.map.map.addOverlay(this.popup2);

            this.bookPanel = {
              bookmarkName: feature.values_.markerInfo.mapBookmarkName,
              bookmarkNote: feature.values_.markerInfo.mapBookmarkRemark,
              imageData: feature.values_.markerInfo.mapBookmarkImage,
            };
            this.popup2.setPosition(feature.values_.geometry.flatCoordinates);
            this.isDetailDialogVisible = true;
          }
        });
      }, 1000); // 延迟 1000 毫秒（1秒）后执行
    },
    clearAllLayers() {
      this.markerLayer.getSource().clear();
      this.markerNameLayer.getSource().clear();
    },
    removeMarkItem(id) {
      deleteBookMark(id).then((res) => {
        this.$message.success("删除成功！");
        this.searchMark();
      });
    },
    markItemDetail(item, index) {
      let elPopup = this.$refs.DetailDialogVisible;
      this.popup2 = new Overlay({
        element: elPopup,
        position: null,
        offset: [0, -8],
        positioning: "bottom-center",
      });

      this.bookPanel = {
        bookmarkName: item.mapBookmarkName,
        bookmarkNote: item.mapBookmarkRemark,
        imageData: item.mapBookmarkImage,
      };
      this.map.map.addOverlay(this.popup2);
      this.popup2.setPosition([item.mapBookmarkX, item.mapBookmarkY]);
      this.isDetailDialogVisible = true;
      this.panToMark(item, index);
    },
    addMarker(item) {
      this.map.marker.addMarker(
        item.lon || item.center[0],
        item.lat || item.center[1],
        this.markerLayer,
        {
          scale: 1.5, //大小
          radius: 15,
          pBorderColor: "#000000",
          pBorderWidth: 1,
          pFillColor: "",
        },
        item
      );
      let elPopup = this.$refs.AddDialogVisible;
      this.popup = new Overlay({
        element: elPopup,
        position: null,
        offset: [0, -10],
        positioning: "bottom-center",
      });
      this.map.map.addOverlay(this.popup);
      this.popup.setPosition([
        item.lon || item.center[0],
        item.lat || item.center[1],
      ]);
      this.showAddBookmarkDialog();
    },
    addMarkerName(item) {
      this.map.marker.addText([item.lon, item.lat], this.markerNameLayer, {
        name: `${item.value ? item.value : ""}`,
        fillColor: "#000000",
        font: "normal 20px 微软雅黑",
        offsetX: 0,
        offsetY: -25,
      });
    },
    //移动到书签所在位置
    panToMark(item, index) {
      this.clearAllLayers();
      this.map.panTo([item.mapBookmarkX, item.mapBookmarkY], 18);
      this.map.marker.addMarker(
        item.mapBookmarkX,
        item.mapBookmarkY,
        this.markerLayer,
        {
          imgUrl: require("@/assets/bookMarker.png"),
          scale: 0.5, //大小
          radius: 1,
          pBorderColor: "#000000",
          pBorderWidth: 1,
          pFillColor: "",
        },
        item
      );
    },
    searchMark() {
      searchBookMark(this.searchValue).then((res) => {
        if (res.code == 200) {
          this.markTableData = res.data;
        }
      });
    },
    enableMapClick() {
      // 移除现有的单击事件监听器
      if (this.addBookmarkListener) {
        this.map.map.un("singleclick", this.addBookmarkListener);
      }

      // 改变鼠标样式为十字光标
      this.map.map.getViewport().style.cursor = "crosshair";
      // 添加地图点击事件监听器
      this.addBookmarkListener = (event) => {
        const coordinate = event.coordinate;
        // 存储点击位置的经纬度
        this.selectedCoordinates = {
          lon: coordinate[0],
          lat: coordinate[1],
        };
        if (!this.isAddDialogVisible) this.addMarker(this.selectedCoordinates);
        // this.showAddBookmarkDialog(); // 显示对话框
      };
      this.map.map.on("singleclick", this.addBookmarkListener);
    },
    restoreDefaultCursor() {
      // 恢复默认鼠标样式
      this.map.map.getViewport().style.cursor = "";
    },
    showAddBookmarkDialog() {
      this.newBookmarkName = ""; // 重置输入框
      this.isAddDialogVisible = true; // 显示对话框
    },
    addBookmark() {
      if (!this.newBookmarkName.trim()) {
        this.$message.warning("请输入书签名称");
        return;
      }
      // ;
      let bookmark = {
        mapBookmarkRemark: this.bookmarkNote,
        mapBookmarkName: this.newBookmarkName,
        mapBookmarkX: this.selectedCoordinates.lon,
        mapBookmarkY: this.selectedCoordinates.lat,
      };
      let file = null;
      let fileData = new FormData();
      if (this.fileList && this.fileList[0]) {
        file = this.fileList[0].raw;
        fileData.append("file", file, file.name);
      }
      fileData.append("mapBookmark", JSON.stringify(bookmark));
      addBookMark(fileData)
        .then((res) => {
          if (res.code == 200 || res.status == 200) {
            this.$message.success("添加书签成功");
            this.searchMark();
          } else {
          }
        })
        .catch((error) => {
          const reader = new FileReader();
          reader.onload = (event) => {
            const text = event.target.result;
            this.$message.error(JSON.parse(text).data);
          };
          reader.readAsText(error.response.data);
        });

      this.isAddDialogVisible = false;
      this.clearAllLayers();

      // 移除监听器
      this.map.map.un("singleclick", this.addBookmarkListener);
      this.addBookmarkListener = null; // 清空监听器
      //恢复鼠标的样式
      this.restoreDefaultCursor();
    },
    // getBookMarkList() {
    //   getBookMarkList().then((res) => {
    //     ;
    //     this.markTableData = res.data;
    //   });
    // },
    closeDetailDialog() {
      this.isDetailDialogVisible = false;
    },
    closeAddDialog() {
      this.isAddDialogVisible = false;

      this.clearAllLayers();
      // 移除监听器
      if (this.addBookmarkListener) {
        this.map.map.un("singleclick", this.addBookmarkListener);
        this.addBookmarkListener = null; // 清空监听器
      }
      //恢复鼠标的样式
      this.restoreDefaultCursor();
    },
  },
  mounted() {
    this.initMap();
    this.createLayer();
    this.searchMark();
  },
  beforeDestroy() {
    this.clearAllLayers();
  },
};
</script>

<style lang="scss" scoped>
/* 添加新增书签对话框样式 */
.add-bookmark-dialog {
  position: absolute;

  color: #fff;
  width: 15rem;

  background-color: #285383;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  z-index: 1000;

  .dialog-content {
    h2 {
      font-size: 1rem;
      font-weight: 400;
      margin-top: 0rem;
    }
    input {
      margin-bottom: 10px;
      padding: 10px;
      width: 100%;
      border: 1px solid #ccc;
      border-radius: 5px;
    }
    button {
      padding: 10px 20px;
      margin-right: 10px;
      border: none;
      border-radius: 5px;
    }
    button:hover {
      opacity: 0.8;
    }
  }
}
.bookmark-form {
  padding: 20px;
}
.form-item {
  margin-bottom: 20px;
}
.form-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
::v-deep .el-col-12 {
  width: 100%;
}
::v-deep .el-upload__tip {
  font-size: 12px;
  color: white;
  margin-top: 7px;
}
.markDialogContainer {
  width: 25vw;
  color: white;
  position: absolute;
  top: 5vh;
  right: -70vw;
  height: 46vh;
  z-index: 2;
  .markDialogTitle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    font-size: 1rem;
    background-color: #285383;
    .title-left,
    .title-right {
      display: flex;
      align-items: center;
    }
    .bar {
      width: 5px; /* 小竖条的宽度 */
      height: 20px; /* 小竖条的高度 */
      background-color: white; /* 小竖条的颜色 */
      margin-right: 10px; /* 小竖条和文字之间的间距 */
    }
    .icon {
      width: 20px; /* 小方框的宽度 */
      height: 20px; /* 小方框的高度 */
      // border: 1px solid #4998f2; /* 小方框的边框 */
      margin-left: 5px; /* 小方框之间的间距 */
    }
    .icon:hover {
      color: #4998f2;
    }
    .icon:focus {
      color: #4998f2;
    }
  }
  .markDialogContent {
    padding: 10px;
    display: flex;
    flex-direction: column;
    background-color: #285383;
    font-size: 0.8rem;
    .contentButton {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px; /* 与下半部分内容的间距 */
      .menuButton {
        width: 50%;
        text-align: center;
      }
      .menuButton.active {
        // color: rgb(8, 46, 82);
        border-bottom: 2px solid white;
      }
    }
    .contentBox {
      width: 100%;
      padding: 10px;
      box-sizing: border-box;
      .formRow {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .search_input {
          width: 485%;
          display: flex;
          align-items: center;
          justify-content: center;
          input {
            width: 80%;
          }
        }
      }
      .formRow1 {
        background-color: #4070a2;
        .search_label {
        }
        .showAllList {
          margin-left: 15vw;
        }
      }
      .formRowPoint {
        display: flex;
        .columnLabel {
          display: flex;
          flex-direction: column;
          .label {
            display: flex;
            .label_text {
              width: 100px;
              margin-right: 10px;
            }
            .coordinate-input {
              margin-left: 88px;
            }
          }
        }
      }
      .formTable {
        .control {
          border: 1px solid white;
          border-bottom: none;
        }
      }
      .label {
        width: 100px;
        margin-right: 10px;
      }
      .control {
        flex-grow: 1;

        .pickup-btn {
          width: 20%;
          margin-left: 1rem;
        }
        .pickup-btn1 {
          margin-left: 12.3rem;
        }
        .smallBtn {
          width: 4.5rem;
        }
        .data-container {
          display: flex;
          justify-content: space-between;
          background-color: #4070a2;
          border-bottom: 1px solid white;
        }
        .data-container:hover {
          background-color: #03366c;
        }
      }
      .controlBtn {
        display: flex;
        justify-content: center;
      }

      select,
      textarea,
      button {
        width: 100%;
        color: white !important;
        background-color: #4070a2;
        border: none; /* 去除边框 */
        outline: none; /* 去除焦点时的轮廓线 */
        font-size: 0.8rem;
        height: 1.5rem;
      }

      button {
        margin-right: 10px; /* 按钮之间的间距 */
      }
      button:hover {
        background-color: #4998f2;
      }
      button:focus {
        background-color: #4998f2;
      }
      textarea {
        height: 5rem;
      }

      /* 最后一行的按钮不需要 label，可以单独设置样式 */
      .formRow:last-child {
        justify-content: flex-end;
      }

      .formRow:last-child .button {
        margin-left: 10px; /* 按钮之间的间距，而不是右边距 */
      }
    }
  }
}
</style>
